import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

///分类筛选页控制器
class ClassifyFilterController extends BaseController with SingleGetTickerProviderMixin {
  ///二级分类列表
  List secondList = [];

  ///tab控制器
  late TabController tabCtr;

  ///商品列表
  List goodsList = [];

  ///商品筛选 0-好评率降序 1-好评率升序 2-销量降序 3-销量升序 4-价格降序 5-价格升序
  int sortType = 0;

  ///当前筛选的索引
  int filterIndex = 0;

  ///筛选列表
  List<Map<String, dynamic>> filterList = [
    {'field': 'total', 'title': "综合排序", 'sort': ""},
    {'field': 'salesNum', 'title': "销量", 'sort': "asc"},
    {'field': 'price', 'title': "价格", 'sort': "asc"},
    {'field': 'rate', 'title': "好评率", 'sort': "asc"},
  ];

  bool isGrid = true;

  ///分页
  @override
  void onInit() async {
    super.onInit();

    tabCtr = TabController(length: secondList.length, vsync: this);
    getTabList();
    goodsList = [];
    setGoodsList(Get.parameters['id']!);
  }

  //获取商品列表
  Future getGoodsList(String id) async {
    Map<String, dynamic> params = {};
    params['classId'] = id;
    params['sid'] = AppData.sid;
    params['pageNum'] = pageNum;
    params['pageSize'] = pageSize;
    params['sortType'] = sortType;
    return await Network.getGoodsList(params);
  }

  ///获取分类tab
  void getTabList() async {
    await Network.getGoodsClassifyDetail(Get.parameters['secondId']!).then((value) {
      secondList = value;
      tabCtr = TabController(length: secondList.length, vsync: this, initialIndex: getIndexById());
      tabCtr.addListener(() async {
        if (tabCtr.index.toDouble() == tabCtr.animation?.value) {
          setGoodsList(secondList[tabCtr.index]['id']);
        }
      });
    }).catchError((error) {});
    update();
  }

  ///根据分类id获取选中的tab索引
  int getIndexById() {
    int index = 0;
    for (int i = 0; i < secondList.length; i++) {
      if (secondList[i]['id'] == Get.parameters['id']) {
        index = i;
      }
    }
    return index;
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    setGoodsList(secondList[tabCtr.index]['id']);
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    if (isLoadData) {}
    setGoodsList(secondList[tabCtr.index]['id'], isAdd: true);
    baseRefreshCtr.loadComplete();
  }

  ///设置商品列表
  void setGoodsList(String id, {bool isAdd = false}) async {
    if (isAdd) {
      pageNum += 1;
      Tools.showLoading();
      Map<String, dynamic> info = await getGoodsList(id);
      Tools.hideLoading();
      isLoadData = pageSize <= info['list'].length ? true : false;
      goodsList.addAll(info['list']);
    } else {
      pageNum = 1;
      Tools.showLoading();
      Map<String, dynamic> info = await getGoodsList(id);
      Tools.hideLoading();
      isLoadData = pageSize <= info['list'].length ? true : false;
      goodsList = [];
      goodsList = info['list'];
    }

    update();
  }

  ///处理筛选字段
  void dealFilterFiled(int index) {
    filterIndex = index;
    Map<String, dynamic> result = filterList[index];
    if (result['sort'] != '') {
      result['sort'] = result['sort'] == 'asc' ? 'desc' : 'asc';
    }
    String filed = result['field'];
    String sort = result['sort'];
    switch (filed) {
      case 'total':
        sortType = 6;
        break;
      case 'salesNum': //销量
        sortType = sort == 'desc' ? 3 : 2;
        break;
      case 'price': //价格
        sortType = sort == 'desc' ? 5 : 4;
        break;
      case 'rate': //好评率
        sortType = sort == 'desc' ? 1 : 0;
        break;
      default:
        sortType = 0;
    }
    setGoodsList(secondList[tabCtr.index]['id']);
  }

  void changeListStyle(boolValue) {
    isGrid = boolValue;
    update();
  }
}
